package com.dangf.app.launcher.service

import android.app.Service
import android.content.Intent
import android.os.IBinder
import com.dangf.app.launcher.app.V.SOCKECT_SERVER_PORT
import com.dangf.app.launcher.app.V.SOCKECT_SERVER_URL
import com.dangf.app.launcher.entity.event.IOEType
import com.dangf.app.launcher.entity.event.IOEvent
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import pw.hais.utils_lib.mina.client.MinaClient
import pw.hais.utils_lib.mina.OnSockectListener
import pw.hais.utils_lib.mina.SockectConfig
import pw.hais.utils_lib.utils.L

/**
 * Created by hais1992 on 2017/9/26.
 */
class SockectService : Service(), OnSockectListener {
    override fun onMessageReceived(message: String?) {

    }

    val minaClient = MinaClient(SockectConfig(SOCKECT_SERVER_URL, SOCKECT_SERVER_PORT!!), this)
    override fun onBind(p0: Intent?): IBinder? {
        return null
    }

    override fun onCreate() {
        super.onCreate()
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this)
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
        stopSelf()
    }

    @Subscribe(threadMode = ThreadMode.BACKGROUND)
    fun onEventMainThreadx(event: IOEvent) {
        L.i("SockectService 收到 BACKGROUND 事件：" + event.type + " -> " + event.obj)
        when (event.type) {
            IOEType.SendSockect -> {
                minaClient.sendMessage(event.obj.toString())
            }
        }
    }

}